package com.attendcollatesys.service.impl;

import com.attendcollatesys.entity.ATDayDetails;
import com.attendcollatesys.entity.ATLeaveExtraDetail;
import com.attendcollatesys.entity.WorkDay;
import com.attendcollatesys.entity.vo.MonthAndAtteDaysHoursVO;
import com.attendcollatesys.entity.vo.OverTimeResultVo;
import com.attendcollatesys.mapper.ATDayDetailMapper;
import com.attendcollatesys.mapper.ATLeaveExtraDetailMapper;
import com.attendcollatesys.mapper.AtMonthTotalsMapper;
import com.attendcollatesys.service.AtteResultsService;
import com.attendcollatesys.service.WorkDayService;
import com.attendcollatesys.util.CountUtil;
import com.attendcollatesys.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AtteResultServiceImpl implements AtteResultsService {


    @Autowired
    private ATDayDetailMapper atDayDetailMapper;

    @Autowired
    private ATLeaveExtraDetailMapper atLeaveExtraDetailMapper;

    @Autowired
    private WorkDayService workDayService;

    @Autowired
    private AtMonthTotalsMapper atMonthTotalsMapper;

    @Override
    public String getInfo(String startDate, String endDate) {
        return null;
    }

    /**
     * 判断一个人 如果每日考情明细有他的记录 的考勤状态
     */
    @Override
    public String checkAttendanceExist(ATDayDetails atDayDetails) {
        if (atDayDetails.getLeaveApplication().equals("Y")) {
            if (atDayDetails.getLeaveType().equals("全天")) {
                return "请假一天";
            } else {
                return "请假半天";
            }
        } else if (atDayDetails.getCheckInTime().isEmpty() || atDayDetails.getSignOutTime().isEmpty()) {
            if (!atDayDetails.getCheckInTime().isEmpty() && LocalTime.parse(atDayDetails.getCheckInTime()).isBefore(LocalTime.of(8, 0))) {
                return "缺勤一天";
            } else {
                return "缺勤半天";
            }
        } else if (LocalTime.parse(atDayDetails.getCheckInTime()).isAfter(LocalTime.of(9, 0))) {
            return "迟到";
        } else {
            return "√";
        }

    }

    /**
     * 判断一个人 如果每日考情明细没有他的记录 但是当日是工作日的考勤状态
     *
     * @param date
     * @param RtxNumber
     * @return
     */
    @Override
    public String checkAttendanceNull(Date date, String RtxNumber) {
        ATLeaveExtraDetail atLeaveExtraDetail = atLeaveExtraDetailMapper.queryByDateAndRtx(date, RtxNumber);

        if (null == atLeaveExtraDetail) {
            return "缺勤一天";
        } else if (date.equals(atLeaveExtraDetail.getStartDay()) && atLeaveExtraDetail.getLeaveStartType().equals("下午")) {
            return "请假半天";
        } else if (date.after(atLeaveExtraDetail.getStartDay()) && date.before(atLeaveExtraDetail.getDeadlineDay())) {
            return "请假一天";
        } else if (date.equals(atLeaveExtraDetail.getDeadlineDay()) && atLeaveExtraDetail.getDeadlineType().equals("上午")) {
            return "请假半天";
        } else {
            return "请假一天";
        }
//        }else if(atLeaveExtraDetail.getStartDay().equals(atLeaveExtraDetail.getDeadlineDay())){
//            if (atLeaveExtraDetail.getLeaveStartType().equals(atLeaveExtraDetail.getDeadlineType())) {
//                return "请假半天";
//            }
//
//
//        }

    }

    /**
     * 构造某一个月 某一个人的考勤结果
     * <b>如果未查询到 返回null<b/>
     *
     * @param yearMonth yyyyMM
     * @param RtxNumber RTX账号
     *
     */
    @Override
    public Map<String, String> buildDetailResult(String yearMonth, String RtxNumber) {
        WorkDay workDays = workDayService.selWorkDayByYrearMonth(yearMonth);
        List<String> workdays = Arrays.stream(workDays.getWorkDay()
                        .split(","))
                .map(o -> yearMonth + o)
                .collect(Collectors.toList());

        List<ATDayDetails> atDayDetailList = atDayDetailMapper.selByAttendanceDateAndRtx(yearMonth, RtxNumber);
        if (atDayDetailList.size() == 0) {
            return null;
        }
        SimpleDateFormat stringDateF = new SimpleDateFormat("yyyyMMdd");

        Map<String, ATDayDetails> atDayDetailsMap = atDayDetailList.stream()
                .collect(Collectors
                        .toMap(o -> stringDateF.format(o.getAttendanceDay()).replace("-", ""), o -> o));

        HashMap<String, String> resultMap = new HashMap<>();

        resultMap.put("name", atDayDetailList.get(0).getName());
        resultMap.put("rtxNumber", RtxNumber);

        int lastDay = Integer.parseInt(atDayDetailMapper.selMaxDayOfMonth(workdays.get(0).substring(0, 4), workdays.get(0).substring(4, 6)));

        for (String workD : workdays) {
            String day = workD.substring(6).startsWith("0") ? workD.substring(7) : workD.substring(6);
            ATDayDetails atDayDetails = atDayDetailsMap.get(workD);
            if (lastDay < Integer.parseInt(day)) {
                //resultMap.put(day,"无记录");
                //如果记录中的最大日期已经小于工作日了 就说明导入的时候就没有记录
                //获取的最大记录日期是从每日考勤明细获取的 如果那个月导入的所有人在最后一天全部请假 这个最大日期获取的就不准确
                //TODO
            } else if (null == atDayDetails) {
                try {
                    resultMap.put(day, checkAttendanceNull(stringDateF.parse(workD), RtxNumber));
                } catch (ParseException e) {
                    throw new RuntimeException("日期转换失败" + workD);
                }
            } else {
                resultMap.put(day, checkAttendanceExist(atDayDetails));
            }
        }
        return resultMap;
    }

    /**
     * 获取考勤结果物
     * add by gzl
     *
     * @param currentMonth yyyy-MM-dd
     * @param name
     * @param rtxNumber
     * @return
     */
    @Override
    public List<Map<String, String>> getDayAttResult(String currentMonth, String name, String rtxNumber) {
        List<String> rtxList = atDayDetailMapper.selRtxByNameDateRtx(currentMonth, name, rtxNumber);
        if (rtxList.isEmpty()) {
            return null;
        }
        String yearMonth = currentMonth.substring(0, 7).replace("-", "");
        List<Map<String, String>> resultList = new ArrayList<>();
        for (String s : rtxList) {
            resultList.add(buildDetailResult(yearMonth, s));
        }
        return resultList;
    }

    /**
     * 获取成果物的 加班结果
     *
     * @param attendanceDate yyyy-MM-dd dd始终为01！
     * @param name
     * @param rtxNumber
     * @return
     */
    @Override
    public List<OverTimeResultVo> buildOTResult(String attendanceDate, String name, String rtxNumber, Integer pageNum, Integer pageSize) {

        List<ATDayDetails> atDayDetailList;
        if (null != pageSize) {
            atDayDetailList = atDayDetailMapper.selOverTimeByRtxNameDate(attendanceDate, name, rtxNumber, pageSize * (pageNum - 1), pageSize);
        } else {
            atDayDetailList = atDayDetailMapper.selOverTimeByRtxNameDate(attendanceDate, name, rtxNumber, null, null);
        }


        if (atDayDetailList.isEmpty()) {
            return null;
        }
        SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat ymdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ArrayList<OverTimeResultVo> resultList = new ArrayList<>();
        for (ATDayDetails atDayDetail : atDayDetailList) {
            OverTimeResultVo overTimeResultVo = new OverTimeResultVo();
            overTimeResultVo.setOvertimeMonth(attendanceDate.substring(5, 7))
                    .setWoName(atDayDetail.getName())
                    .setOvertimeDate(ymd.format(atDayDetail.getEffectiveEndTime()))
                    .setStartTime(ymdt.format(atDayDetail.getEffectiveStateTime()))
                    .setEndTime(ymdt.format(atDayDetail.getEffectiveEndTime()))
                    .setNotes(atDayDetail.getOvertimeContent())
                    .setRtxNumber(atDayDetail.getRtxNumber());


            overTimeResultVo.setDuration(CountUtil.calOverTimeHours(TimeUtil.countHourDiffer(atDayDetail.getEffectiveEndTime(), atDayDetail.getEffectiveStateTime())));
            resultList.add(overTimeResultVo);
        }
        return resultList;
    }

    @Override
    public Map<Object, Object> selOneAtteCount(String rtxNumber, String[] date) {
        ArrayList<Map<Object, Object>> monthAndAttedaysList = new ArrayList<>();
        ArrayList<Map<Object, Object>> monthAndhoursList = new ArrayList<>();
        String name="";
        for (String tempDate : date) {
            HashMap<Object, Object> monthAndAttedaysMap = new HashMap<>();
            HashMap<Object, Object> monthAndhoursMap = new HashMap<>();
            Map<String, String> atteMap = buildDetailResult(tempDate.replace("-","").substring(0,6), rtxNumber);
            if (null == atteMap) {
                continue;
            }
            MonthAndAtteDaysHoursVO monthAndAtteDaysHoursVOS = atMonthTotalsMapper.selMonthAtteDHVOByRtx(rtxNumber, tempDate);
            double holidays=0;
            int absent=0;
            for (String status : atteMap.values()) {
                if(status.equals("请假一天")){
                    holidays++;
                }else if(status.equals("请假半天")){
                    holidays+=0.5;
                }else if(status.startsWith("缺勤")||status.equals("迟到")) {
                    absent++;
                }
            }
            monthAndAttedaysMap.put("monthDay",tempDate.substring(0,7));
            monthAndAttedaysMap.put("required", monthAndAtteDaysHoursVOS.getRequired());
            monthAndAttedaysMap.put("reality", monthAndAtteDaysHoursVOS.getReality());
            monthAndAttedaysMap.put("leave", String.valueOf(holidays));
            monthAndAttedaysMap.put("lateEarly", String.valueOf(absent));
            monthAndAttedaysList.add(monthAndAttedaysMap);
            monthAndhoursMap.put("monthHour",tempDate.substring(0,7));
            monthAndhoursMap.put("requiredHours",monthAndAtteDaysHoursVOS.getRequiredHours());
            monthAndhoursMap.put("realityHours",monthAndAtteDaysHoursVOS.getRealityHours());
            monthAndhoursMap.put("overHours", monthAndAtteDaysHoursVOS.getOverHours());
            monthAndhoursList.add(monthAndhoursMap);
            name = monthAndAtteDaysHoursVOS.getName();


        }
        HashMap<Object, Object> result = new HashMap<>();
        result.put("name", name);
        result.put("monthAndAttedaysList",monthAndAttedaysList);
        result.put("monthAndhoursList", monthAndhoursList);



        return result;

    }


}
